<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="门票名称" prop="ticketName">
        <el-input
          v-model="queryParams.ticketName"
          placeholder="请输入门票名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门票编号" prop="ticketCode">
        <el-input
          v-model="queryParams.ticketCode"
          placeholder="请输入门票编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="门票类型" prop="ticketType">
        <el-select v-model="queryParams.ticketType" placeholder="请选择门票类型" clearable size="small">
          <el-option
            v-for="dict in dict.type.ticket_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['bussiness:ticket:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['bussiness:ticket:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['bussiness:ticket:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['bussiness:ticket:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="ticketList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="门票名称" align="center" prop="ticketName" />
      <el-table-column label="门票编号" align="center" prop="ticketCode" />
      <el-table-column label="门票描述" align="center" prop="ticketDescription" />
      <el-table-column label="门票价格(元)" align="center" prop="ticketPrice" />
      <el-table-column label="门票时长(小时)" align="center" prop="ticketDuration" />
      <el-table-column label="门票类型" align="center" prop="ticketType">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.ticket_type" :value="scope.row.ticketType"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handlePurchase(scope.row)"
            v-hasPermi="['bussiness:ticket:purchase']"
          >预约门票</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['bussiness:ticket:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['bussiness:ticket:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改门票信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="130px">
        <el-form-item label="门票名称" prop="ticketName">
          <el-input v-model="form.ticketName" placeholder="请输入门票名称" />
        </el-form-item>
        <el-form-item label="门票编号" prop="ticketCode">
          <el-input v-model="form.ticketCode" placeholder="请输入门票编号" />
        </el-form-item>
        <el-form-item label="门票类型" prop="ticketType">
          <el-select v-model="form.ticketType" placeholder="请选择门票类型" class="full-width">
            <el-option
              v-for="dict in dict.type.ticket_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="门票描述" prop="ticketDescription">
          <el-input v-model="form.ticketDescription" placeholder="请输入门票描述" />
        </el-form-item>
        <el-form-item label="门票价格(元)" prop="ticketPrice">
          <el-input v-model.number="form.ticketPrice" placeholder="请输入门票价格" />
        </el-form-item>
        <el-form-item label="门票时长(小时)" prop="ticketDuration">
          <el-input v-model.number="form.ticketDuration" placeholder="请输入门票时长" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog :title="purchase.title" :visible.sync="purchase.open" width="580px" append-to-body>
      <el-form ref="purchaseForm" :model="purchase.form" :rules="purchase.rules" label-width="80px">
        <el-form-item label="预约日期" prop="date" >
          <el-date-picker
           @change="getPickerStartTime(true)"
            v-model="purchase.form.date"
            type="date"
            placeholder="选择日期"
            :picker-options="pickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="预约时间" prop="time">
          <el-time-select
            placeholder="起始时间"
            v-model="purchase.form.startTime"
            :picker-options="{
              start: pickerStartTime,
              step: '00:15',
              end: pickerEndTime
            }">
          </el-time-select> ~ 
          <el-time-select
            disabled
            placeholder="结束时间"
            v-model="purchaseEndTime"
            :picker-options="{
              start: purchaseEndTime,
              end: purchaseEndTime
            }">
          </el-time-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitPurchase">确 定</el-button>
        <el-button @click="cancelPurchase">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listTicket, getTicket, delTicket, addTicket, updateTicket } from "@/api/bussiness/ticket";
import { addPurchase } from '@/api/bussiness/purchase';

export default {
  name: "Ticket",
  dicts: ['ticket_type'],
  data() {
    return {
      // 预约时间 开始时间
      pickerStartTime: '08:00',
      // 预约时间 截至时间
      pickerEndTime: '21:00',
      // 可选日期空间
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now() - 24*60*60*1000;
        }
      },
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 门票信息表格数据
      ticketList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ticketName: null,
        ticketCode: null,
        ticketType: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        ticketName: [
          {required: true, message: '请填写门票名称', blur: 'change'}
        ],
        ticketCode: [
          {required: true, message: '请填写门票编号', blur: 'change'}
        ],
        ticketPrice: [
          {required: true, type: 'number', message: '请正确填写门票价格', blur: 'change'}
        ],
        ticketDuration: [
          {required: true, type: 'number', message: '请正确填写门票时长', blur: 'change'}
        ],
        ticketType: [
          {required: true, message: '请选择门票类型', blur: 'change'}
        ],
      },
      // 预约购买
      purchase: {
        title: '预约门票',
        open: false,
        form: {
        },
        rules: {
        }
      },
      // 定时器
      timer: '',
      // 当前点击门票信息
      currentTicketRow: '',
    };
  },
  created() {
    this.getList();
  },
  mounted(){
    this.timer = setInterval(()=> {this.getPickerStartTime()}, 30000)
  },
  beforeDestroy(){
    clearInterval(this.timer)
  },
  computed: {
    purchaseEndTime: function (){
      if(this.purchase.form.startTime){
        let time = this.purchase.form.startTime.split(':')
        let tmp_hour = time[0] / 1 + this.currentTicketRow.ticketDuration
        let tmp_min = time[1] / 1
        // 判断是否超过结束时间
        let endT = this.pickerEndTime.split(':')
        if(tmp_hour >= endT[0]){
          tmp_hour = endT[0]
          tmp_min = endT[1]
        }
        return tmp_hour + ':' + (tmp_min == 0? '00' : tmp_min)
      }
    },
  },
  methods: {
    // 获取可选开始时间
    getPickerStartTime(refresh){
      if(refresh){
        this.$set(this.purchase.form, 'startTime', '')
      }
      // 如果预约日期是今天，做处理。如果是明天，不用做处理
      let dt = this.purchase.form.date
      if(dt){
        let ndt = new Date()
         if(dt.getFullYear() == ndt.getFullYear() && dt.getMonth() == ndt.getMonth() && dt.getDate() == ndt.getDate()){
            let hh = new Date().getHours()
            let mm = new Date().getMinutes()
            let tmp_hh, tmp_mm
            tmp_hh = hh
            // 如果分钟大于45，小时+1
            if(mm < 15){
              tmp_mm = '15'
            }else if( 15 < mm && mm < 30){
              tmp_mm = '30'
            }else if( 30 < mm && mm < 45){
              tmp_mm = '45'
            }else if( mm >= 45){
              tmp_mm = '00'
              tmp_hh = hh + 1
            }
            console.log(tmp_hh + ":" + tmp_mm)
            return this.pickerStartTime = tmp_hh + ":" + tmp_mm
         }
      }
      return this.pickerStartTime = '08:00'
    },
    /** 查询门票信息列表 */
    getList() {
      this.loading = true;
      listTicket(this.queryParams).then(response => {
        this.ticketList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ticketId: null,
        ticketName: null,
        ticketCode: null,
        ticketDescription: null,
        ticketPrice: null,
        ticketDuration: null,
        ticketType: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ticketId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加门票信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ticketId = row.ticketId || this.ids
      getTicket(ticketId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改门票信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ticketId != null) {
            updateTicket(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTicket(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ticketIds = row.ticketId || this.ids;
      this.$modal.confirm('是否确认删除门票信息编号为"' + ticketIds + '"的数据项？').then(function() {
        return delTicket(ticketIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('bussiness/ticket/export', {
        ...this.queryParams
      }, `ticket_${new Date().getTime()}.xlsx`)
    },
    /** 预约按钮操作 */
    handlePurchase(row){
      console.log(row)
      this.currentTicketRow = row
      this.getPickerStartTime()
      this.purchase.open = true
    },
    submitPurchase(){
        const {ticketId, ticketPrice, ticketCode, ticketType} = this.currentTicketRow
        const {date, startTime} = this.purchase.form
        if(!date){
          return this.$modal.msgError("请填写预约日期！")
        }
        if(!startTime){
          return this.$modal.msgError("请填写预约时间！")
        }
        let comDate = date.getFullYear() + '-' 
          + ((date.getMonth() + 1) < 10 ? '0'+ (date.getMonth() + 1) : date.getMonth() + 1) + '-' 
          + (date.getDate() < 10 ? '0' + date.getDate() : date.getDate())
        let ticketStartTime = comDate + ' ' + startTime + ':00'
        let ticketEndTime = comDate + ' ' + this.purchaseEndTime + ':00'
        let params = {
          ticketId,
          purchaseMoney: ticketPrice,
          ticketStartTime,
          ticketEndTime
        }
        addPurchase(params).then(res=>{
          this.$modal.msgSuccess("新增成功");
          this.purchase.form = {}
          this.purchase.open = false;
        })
    },
    cancelPurchase(){
      this.purchase.form = {}
      this.purchase.open = false
    }
  }
};
</script>
